<?php

/**
 * @desc 分页导航显示类
 * 
 * @author keluo <pycorvn@yeah.net>
 * @link http://www.scabish.cn/framework
 * @since 2011-5-28 2:11:29
 */
class SCPaging {
	
	protected static $currentPage; // 当前页码
	public static $numRecord; // 记录总数
	public static $recordPerPage = 10; // 每页显示记录数
	public static $maxPageShow = 5; // 导航显示最大分页栏数
	
	/**
	 * 获取当前页码
	 */
	public static function getCurrentPage() {
		if(!self::$currentPage) {
			self::setCurrentPage();
		}
		
		return self::$currentPage;
	}
	
	/**
	 * 获取每页显示记录数
	 */
	public static function getRecordPerPage() {
		return self::$recordPerPage;	
	}
	
	/**
	 * 设置当前页码
	 */
	public static function setCurrentPage() {
		 self::$currentPage = SCRequest::get('page') ? SCRequest::get('page') : 1;
	}
	
	/**
	 * 设置记录总数
	 */
	public static function setNumRecord($numRecord) {
		self::$numRecord = $numRecord;
	}
	
	/**
	 * 设置每页显示记录数
	 */
	public static function setRecordPerPage($recordPerPage) {
		self::$recordPerPage = $recordPerPage;
	}
	
	/**
	 * 设置导航显示最大分页栏数
	 */
	public static function setMaxPageShow($maxPageShow) {
		self::$maxPageShow = $maxPageShow;
	}
	

	/**
	 * 获取分页导航串形如：<< 2 3 4 5 ６ 7 8 9 10 11 >>
	 * @return string HTML形式的分页导航链接
	 */									
	public static function create($numRecord = 0, $recordPerPage = 0, $maxPageShow = 0) {
		self::$numRecord = $numRecord ? $numRecord : self::$numRecord;
		self::$recordPerPage = $recordPerPage ? $recordPerPage : self::$recordPerPage;
		self::$maxPageShow = $maxPageShow ? $maxPageShow : self::$maxPageShow;
		self::setCurrentPage();
		
		$url = self::genUrl();
		$totalPage = ceil(self::$numRecord / self::$recordPerPage);		
		$numToShow = min($totalPage - 1, self::$maxPageShow-1);
	
		$firstIdx = max(1, self::$currentPage - floor($numToShow/2));
		if($firstIdx + $numToShow > $totalPage) {
			$firstIdx = max(1, $totalPage - $numToShow);
		}

		$link = '';
		if($totalPage <= 1) {
			return $link;
		}
		
		$link .= '<li'.((self::$currentPage == 1) ? ' class="prev disabled"' : '').'><a href="'.$url.'/page/1">&laquo;</a></li>';
		for($i = $firstIdx; $i <= $numToShow + $firstIdx; $i++) {
			$selected = self::$currentPage == $i;
			$link .= '<li'.($selected ? ' class="active"' : '').'>';
			$link .= '<a href="'.$url.'/page/'.$i.'">'.$i.'</a>';
			$link .= '</li>';
			
		}
		$link .= '<li'.((self::$currentPage == $totalPage) ? ' class="prev disabled"' : '').'><a href="'.$url.'/page/'.$totalPage.'">&raquo;</a></li>';
		return $link;
	}
	
	/**
	 * @todo 从$_REQUEST里面取值遍历
	 * @return string
	 */
	protected static function genUrl() {
		$url = SCRequest::getBaseURI().'/';
		$url = rtrim($url, '/');
		$url .= '/'.SCRequest::getControllerName().'/'.SCRequest::getActionName();
		foreach(SCRequest::get() as $key=>$value) {
			if($key == 'page') continue;
			$url .= '/'.$key.'/'.$value;
		}
		
		return $url;
	}
}